package com.tastespot.utils;


import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tastespot.model.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.tastespot.constants.RedisConstants.*;

/**
 * @Author: 369pro
 * @CreateTime: 2025-05-17
 * @Version: 1.0
 */
@Component
@Slf4j
public class CacheClient {
    @Resource
    private RBloomFilter<String> bloomFilter;

    private final StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     *  布隆过滤器 解决缓存穿透问题
     *  根据id查找db相应内容
     */
    public <R, ID> R queryWithPassThrough(
            String prefix, ID id, Class<R> type, Function<ID, R> dbFunc, Long time, TimeUnit unit){
        String cacheKey = prefix + id;
        if(!bloomFilter.contains(cacheKey)){
            return null;
        }
        // 1. 查询redis
        String shopJson = stringRedisTemplate.opsForValue().get(cacheKey);
        if(StrUtil.isNotBlank(shopJson)){
            return JSONUtil.toBean(shopJson, type);
        }
        // 2. 查不到redis, 查询db
        R r = dbFunc.apply(id);
        if(Objects.isNull(r)){
            return null;
        }
        // 3. 更新db数据到 redis和布隆过滤器 中
        this.set(cacheKey, r, time, unit);
        bloomFilter.add(cacheKey);
        return r;
    }

    /**
     *  缓存击穿问题：1. 基于逻辑过期方式解决
     */
    public <T, ID> T queryWithLogicalExpire(
            String prefix, ID id, Class<T> type, Function<ID, T> dbFunc, Long timeout, TimeUnit unit){
        String cacheKey = prefix + id;
        String jsonStr = stringRedisTemplate.opsForValue().get(cacheKey);
        // 1. 未命中缓存，直接返回空
        if(StrUtil.isBlank(jsonStr)){
            return null;
        }
        RedisData redisData = JSONUtil.toBean(jsonStr, RedisData.class);
        T t = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        // 2. 未过期，返回缓存信息
        if(redisData.getExpireTime().isAfter(LocalDateTime.now())){
            return t;
        }
        String lockKey = LOCK_SHOP_KEY + id;
        // 3. 已过期，尝试获取互斥锁
        boolean isLock = tryLock(lockKey);
        // 3.1 获取锁成功，开启异步线程
        if(isLock){
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try{
                    T newt = dbFunc.apply(id);
                    this.setWithLogicalExpire(cacheKey, newt, timeout, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }
            });
        }
        // 3.2 获取锁失败 double check 与 queryWithMutex 一样
        jsonStr = stringRedisTemplate.opsForValue().get(cacheKey);
        if(StrUtil.isBlank(jsonStr)){
            return null;
        }
        redisData = JSONUtil.toBean(jsonStr, RedisData.class);
        t = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        // todo不管过期与否，返回的都是redis里的信息 会返回旧数据
        return t;
    }

    public <T, ID> T queryWithMutex(
            String prefix, ID id, Class<T> type, Function<ID, T> dbFunc, Long timeout, TimeUnit unit){
        String cacheKey = CACHE_SHOP_KEY + id;
        // 1、从Redis中查询店铺数据，并判断缓存是否命中
        String jsonStr = stringRedisTemplate.opsForValue().get(cacheKey);
        if(StrUtil.isNotBlank(jsonStr)){
            // 缓存命中，直接返回
            return JSONUtil.toBean(jsonStr, type);
        }
        // 2. 未命中，实现缓存重构
        // 2.1. 判断能否获得互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        T t = null;
        try{
            boolean isLock = tryLock(lockKey);
            // 获取锁失败，休眠一段时间
            if(!isLock){
                Thread.sleep(50);
                // todo 此处建议改成循环，我先这样写了
                return queryWithMutex(prefix, id, type, dbFunc, timeout, unit);
            }
            // note 4：多线程环境下此处需要double check 如果存在则无需重建缓存(之前的请求线程已经完成重建)
            jsonStr = stringRedisTemplate.opsForValue().get(cacheKey);
            if(StrUtil.isNotBlank(jsonStr)){
                // 缓存命中，直接返回
                return JSONUtil.toBean(jsonStr, type);
            }
            t = dbFunc.apply(id);
            // 4、判断数据库是否存在店铺数据
            if (Objects.isNull(t)) {
                // 4.1 数据库中不存在，返回失败信息
                return null;
            }
            // 添加动态ttl
            this.set(cacheKey, JSONUtil.toJsonStr(t),
                    CACHE_SHOP_TTL*60 + new Random(System.currentTimeMillis()).nextInt(100), TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            unlock(lockKey);
        }
        return t;
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        // 拆箱要判空，防止NPE
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
